﻿using System;
using System.Windows.Forms;
using Alerter.DataSet;
using DevExpress.XtraGrid.Views.Grid;

namespace Alerter.Controls
{
    public partial class QueryListUserControl : UserControl, IList, IGridView
    {
        private Controller _controller;

        #region Properties

        public Controller Controller
        {
            set
            {
                _controller = value;
                _controller.QuerySaved += delegate { SetGridDataSource(); };
                SetGridDataSource();
            }
        }

        #endregion

        public QueryListUserControl()
        {
            InitializeComponent();
            gridView.DoubleClick += GridViewDoubleClick;
        }

        #region Private Methods

        private void SetGridDataSource()
        {
            QueryDataSet dataSet = _controller.GetQueries();
            gridControl.DataSource = null;
            gridControl.DataSource = dataSet;
            gridControl.DataMember = dataSet.Query.TableName;
        }

        private void ShowDocument(long documentId)
        {
            var window = new QueryXtraForm { DocumentId = documentId, Controller = _controller };
            window.ShowDialog();
        }


        #endregion

        public void AddDocument()
        {
            ShowDocument(-1);
        }

        public void DeleteDocument()
        {
            var document = (QueryDataSet.QueryRow)gridView.GetDataRow(gridView.FocusedRowHandle);
            if (document == null)
                return;
            var result = MessageBox.Show(_controller.OwnerWindow, string.Format("'{0}' será eliminada definitivamente.", document.Nome), 
                "Query", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);
            if(result != DialogResult.OK)
                return;
            _controller.DeleteQuery(document.Id);
        }

        void GridViewDoubleClick(object sender, EventArgs e)
        {
            var document = (QueryDataSet.QueryRow)gridView.GetDataRow(gridView.FocusedRowHandle);
            if (document == null)
                return;
            ShowDocument(document.Id);
        }

        public GridView GridView()
        {
            return gridView;
        }

        public string ListName
        {
            get { return "QueryListUserControl"; }
        }
    }
}
